function [Rc, C, Rs, S, O] = get_original_value2(img, qtable)
%GET_ORIGINAL_VALUE calculates non-round DCT coeffients.
% Usage :
%  [RC, C, RS, S, O] = GET_ORIGINAL_VALUE(IMG, QTABLE)
%  Calculates values of R, C, O, S in MME papers.
%  Rc -> R (c''-c') (rounding errors)
%  C  -> c''        (rounded coeffients)
%  Rs -> S - C'     (rounding errors + embedding errors)
%  S  -> c''        (embeded coeffients, with every value CHANGED)
%  O  -> c'         (non-round DCT coeffients)
%

    %% calculate C' C''
    O = nonround_dct(img, qtable);
    [P, Q] = size(O);
    C = round(O);
    Rc = C - O;
    
    %% calcuate S (e.g. embedding in every bit)
    S = zeros(P, Q);
    for i = 1:P
        for j = 1:Q
            if Rc(i,j) < 0
                S(i,j) = C(i,j) + 1;
            else % Rc(i,j) > 0
                S(i,j) = C(i,j) - 1;
            end
        end
    end
    Rs = S - O;
    
    assert(max(max(abs(S - C))) <= 1);
end

function coef = nonround_dct(img, qtable)
    if size(img,3) ~= 1
        img = rgb2gray(img);
    end
    [M,N] = size(img);
    P = ceil(M / 8)*8;
    Q = ceil(N / 8)*8;
    pad = zeros(P, Q);% padding
    pad(1:M, 1:N) = img;   
    clear img;
    fun = @(block_struct) dct2(block_struct.data) ./ qtable;% DCT
    coef = blockproc(pad - 128,[8 8], fun);
end

